<?php

namespace App\Http\Middleware;

use Closure;
//use Illuminate\Support\Facades\Auth;
use App\Services\AccessTokenService;
//use Illuminate\Contracts\Auth\Factory as Auth;

class ApiTokenAuthenticate
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    //protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    //public function __construct(Auth $auth)
    //{
    //    $this->auth = $auth;
    //}

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($request->hasHeader('user-id') && $request->hasHeader('user-token') && $request->hasHeader('app')) {
            $userId = $request->header('user-id');
            $userToken = $request->header('user-token');
            $appId = $request->header('app');

            $accessTokenService = new AccessTokenService();

            if (!$accessTokenService->isTokenValid($userId, $appId, $userToken, $request->ip)) {
                return response('用户请求未验证通过', 401);
            }

        } else {
            return response('本次请求必须验证用户身份和用户登录令牌', 401);
        }

        return $next($request);
    }
}
